package kvraft

import (
	"6.824/labrpc"
	"6.824/utils"
	"log"
	"time"
)
import "crypto/rand"
import "math/big"

type Clerk struct {
	servers []*labrpc.ClientEnd

	lstLeader int
	// You will have to modify this struct.
}

func nrand() int64 {
	max := big.NewInt(int64(1) << 62)
	bigx, _ := rand.Int(rand.Reader, max)
	x := bigx.Int64()
	return x
}

func MakeClerk(servers []*labrpc.ClientEnd) *Clerk {
	ck := new(Clerk)
	ck.servers = servers

	ck.lstLeader = 0
	// You'll have to add code here.
	return ck
}

//
// fetch the current value for a key.
// returns "" if the key does not exist.
// keeps trying forever in the face of all other errors.
//
// you can send an RPC with code like this:
// ok := ck.servers[i].Call("KVServer.Get", &args, &reply)
//
// the types of args and reply (including whether they are pointers)
// must match the declared types of the RPC handler function's
// arguments. and reply must be passed as a pointer.
//
func (ck *Clerk) Get(key string) string {
	args := GetArgs{key}
	//log.Printf("get args:%v", args)
	reply := ck.Call("Get", &args).(*GetReply)
	utils.Assert(reply.Err == OK || reply.Err == ErrNoKey)
	//log.Printf("get:%v", reply)
	return reply.Value
	// You will have to modify this function.
}

//
// shared by Put and Append.
//
// you can send an RPC with code like this:
// ok := ck.servers[i].Call("KVServer.PutAppend", &args, &reply)
//
// the types of args and reply (including whether they are pointers)
// must match the declared types of the RPC handler function's
// arguments. and reply must be passed as a pointer.
//
func (ck *Clerk) PutAppend(key string, value string, op string) {

	p := nrand()
	args := PutAppendArgs{p, key, value, op}
	//log.Printf("putappend args:%v", args)
	reply := ck.Call("PutAppend", &args).(*PutAppendReply)

	utils.Assert(reply.Err == OK)

	cargs := ConfirmArgs{p}
	creply := ck.Call("Confirm", &cargs).(*ConfirmReply)
	utils.Assert(creply.Err == OK)
	//log.Printf("putappend:%v args:%v", reply, args)
	// You will have to modify this function.
}
func (ck *Clerk) Call(method string, args interface{}) interface{} {
	var reply interface{}

	for i := ck.lstLeader; ; i = (i + 1) % len(ck.servers) {
		switch method {
		case "PutAppend":
			reply = &PutAppendReply{}
		case "Get":
			reply = &GetReply{}
		case "Confirm":
			reply = &ConfirmReply{}
		default:
			panic("wrong method")
		}
		ok := ck.servers[i].Call("KVServer."+method, args, reply)
		//log.Printf("recv reply")
		if !ok || reply.(BaseReply).GetErr() == ErrWrongLeader {
			continue
		}
		ck.lstLeader = i
		if reply.(BaseReply).GetErr() == OK {
			return reply
		} else if reply.(BaseReply).GetErr() == ErrNoKey {
			reply.(*GetReply).Value = ""
			return reply
		} else if reply.(BaseReply).GetErr() == ErrFailToCommit {
			i--
			time.Sleep(time.Millisecond * retryInterval)
			continue
		} else {
			log.Fatalf("wrong err code:%v", reply.(BaseReply).GetErr())
		}

	}
}

func (ck *Clerk) Put(key string, value string) {
	ck.PutAppend(key, value, "Put")
}
func (ck *Clerk) Append(key string, value string) {
	ck.PutAppend(key, value, "Append")
}
